<template>
  <div class="cart">
    <div class="nav_bar">
      <van-nav-bar
        title="购物车"
        :right-text="isShow ? '完成' : '编辑'"
        @click-right="isShow = !isShow"
      />
    </div>
    <div class="cart_list">
      <van-card
        v-for="item in cartlist"
        :price="item.goods_price"
        :title="item.goods_name"
        :key="item.goods_id"
      >
        <template #thumb>
          <van-checkbox
            v-model="item.is_select"
            @click="changeOne(item.goods_id, item.is_select)"
          ></van-checkbox>
          <van-image
            width="90"
            height="90"
            :src="item.goods_big_logo"
            @click="goGoods('/goods/' + item.goods_id)"
          />
        </template>
        <template #footer>
          <van-stepper
            v-model="item.Cartcount"
            :name="item.goods_id"
            @change="uplist"
            disable-input
          />
        </template>
      </van-card>
    </div>
    <div class="submit_order">
      <van-submit-bar
        :disabled="isSelect()"
        :price="calculation"
        button-text="去结算"
        @submit="goCheckout"
        v-show="!isShow"
      >
        <van-checkbox v-model="allcheck" @click="changeAll">全选</van-checkbox>
      </van-submit-bar>
      <van-submit-bar v-show="isShow">
        <template #button>
          <van-button
            round
            type="danger"
            @click="remove"
            :disabled="isSelect()"
          >
            <van-icon name="delete-o" />
            删除
          </van-button>
        </template>
        <van-checkbox v-model="allcheck">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>
<script>
let flag_uplist = true;
let flag_check = true;
export default {
  name: "Cart",
  data() {
    return {
      // 提交与删除切换
      isShow: false,
      // 今日推荐商品
      goodslist: [],
      value: 1,
    };
  },
  methods: {
    // 点击商品跳转商品页
    goGoods(goods) {
      this.$router.push(goods);
    },
    // 获取购物车全部信息
    getCart() {
      this.$request
        .post(
          "/getCart",
          {
            username: this.userInfo.username,
          },
          {
            headers: {
              token: this.userInfo.token,
            },
          }
        )
        .then(({ data }) => {
          //请求成功将购物车信息保存至本地
          this.goodslist = data.data;
          if (data.status == 200) {
            data.data.forEach((item) => {
              if (item.is_select === "true") {
                item.is_select = true;
              } else {
                item.is_select = false;
              }
            });

            this.$store.commit("cart/addToLocal", data.data);
          }
        });
    },
    // 删除商品
    remove() {
      // 删选已勾选商品
      let ids = [];
      this.cartlist.forEach((item) => {
        if (item.is_select) {
          ids.push(item.goods_id);
        }
      });
      this.$dialog
        .confirm({
          message: `确定删除${ids.length}件商品？`,
        })
        .then(() => {
          this.$request
            .post(
              "/delFromCart",
              { username: this.userInfo.username, delIds: ids },
              {
                headers: {
                  token: this.userInfo.token,
                },
              }
            )
            .then(({ data }) => {
              if (data.status == 200) {
                this.$store.commit("cart/removeFromCart", ids);
              }
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    // 修改商品数量
    uplist(num, id) {
      if (flag_uplist) {
        flag_uplist = false;
        this.$request
          .post(
            "/updateCartCount",
            {
              username: this.userInfo.username,
              id: id.name,
              num: num,
            },
            {
              headers: { token: this.userInfo.token },
            }
          )
          .then(({ data }) => {
            if (data.status == 200) {
              this.$store.commit("cart/changeQty", {
                goods_id: id.name,
                Cartcount: num,
              });
              flag_uplist = true;
            }
          });
      }
    },
    //跳转结算
    goCheckout() {
      this.$router.push({
        name: "SubOrder",
        query: { flag: "cart" },
      });
    },
    // 是否选择商品决定提交与删除的可用性
    isSelect() {
      return !this.cartlist.some((item) => item.is_select);
    },
    // 修改全部是否选择
    async changeAll() {
      if (flag_check) {
        flag_check = false;
        const data = await this.updateCartChecked("all", this.allcheck);
        this.$store.commit("cart/checkAll", this.allcheck);
        flag_check = true;
      }
    },
    // 修改单个是否选择
    async changeOne(id, checked) {
      if (flag_check) {
        flag_check = false;
        const data = await this.updateCartChecked(id, checked);
        this.$store.commit("cart/checkOne", checked);
        flag_check = true;
      }
    },
    // 修改购物车选择状态请求
    async updateCartChecked(id, checked) {
      const { data } = await this.$request.post(
        "/updateCartChecked",
        {
          username: this.userInfo.username,
          id: id,
          Checked: checked,
        },
        {
          headers: { token: this.userInfo.token },
        }
      );
      return data;
    },
  },
  created() {
    // 进入购物车页面请求购物车数据
    this.getCart();
  },
  destroyed() {},
  computed: {
    // 计算总价
    calculation() {
      return (
        this.cartlist
          .filter((item) => item.is_select)
          .reduce((pre, item) => {
            return pre + item.goods_price * item.Cartcount;
          }, 0) * 100
      );
    },
    // 全选
    allcheck: {
      get() {
        if (!this.cartlist.length) return false;
        return this.cartlist.every((item) => item.is_select);
      },
      set(n, o) {
        // return !n;
        this.$store.commit("cart/checkAll", n);
      },
    },
    // 获取本地购物车数据
    cartlist() {
      return this.$store.state.cart.cartlist;
    },
    // 获取本地用户信息
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
};
</script>
<style lang="scss" scoped>
.cart {
  padding-bottom: 100px;
  padding-top: 46px;
  .van-nav-bar {
    position: fixed;
    width: 100%;
    top: 0;
  }
  .van-card {
    .van-card__header {
      text-align: left;
      .van-card__thumb {
        width: 120px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
    .van-card__footer {
      .van-button {
        margin: 0;
      }
    }
  }
  .van-nav-bar {
    .van-nav-bar__title {
      font-size: 20px;
      font-weight: bold;
    }
  }
}
.van-submit-bar {
  bottom: 50px;
  .van-submit-bar__bar {
    justify-content: space-between;
  }
}
.van-card__price {
  color: orangered;
}
.van-card__content {
  padding-top: 15px;
}
</style>